<template>
  <div class="emerDrillPlan">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger"
                     size="small"
                     icon="el-icon-delete"
                     plain
                     v-if="permission.drillplan_delete"
                     @click="handleDelete">删 除
          </el-button>
        </template>

        <!-- 核实人表格自定义 -->
        <template slot="pjsz" slot-scope="scope">
          <div>
            <el-button v-if="scope.row['pjr'] === ''||scope.row['pjr']===undefined" type="warning" size="mini" @click="handleVerifier(scope.row)">添加评价人</el-button>
            <span v-else>-</span>
          </div>
        </template>
        <!-- 发布 -->
        <template slot="fbzt" slot-scope="scope">
          <div v-if="scope.row['fbzt']=='0'||scope.row['fbzt']===undefined">
            <el-form label-width="0px">
              <el-button v-if="scope.row['pjr']!==''" type="primary" size="small" @click="publishPlan(scope.row['id'])" plain>发布</el-button>
              <span v-else>-</span>
            </el-form>
          </div>
          <div v-else>
            <el-button type="success" size="small" plain >已发布</el-button>
          </div>
        </template>

        <!-- 演练评价信息查看 -->
        <template slot="ylpjxx" slot-scope="scope">
          <div>
            <el-form label-width="0px">
              <el-button type="success" size="small" @click="viewDrill">查看</el-button>
            </el-form>
          </div>
        </template>

        <!-- 相关附件表格自定义 -->
        <template slot="xgfj" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['xgfj']">
              <i class="el-icon-download"></i>下载附件
            </a>
          </div>
        </template>

        <!-- 相关附件表单自定义 -->
        <template slot="xgfjForm">
          <div>
            <el-upload action="/api/fileManager/upload/file" :headers="SetHeaders" :file-list="xgfjFileList"
                       :before-upload="beforeUploadXGFJ"
                       :on-remove="handleRemoveXGFJ"
                       :on-success="uploadXGFJSuccess">
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </template>
      </avue-crud>

      <!-- 弹窗：添加核实人 -->
      <el-dialog
        title="添加核实人"
        append-to-body
        :visible.sync="verifierDialog"
        :close-on-click-modal="false"
        :before-close="closeVerifierDialog"
        width="60%"
        class="add_violation_dialog"
      >
        <avue-form
          ref="updateForm"
          v-model="updateObj"
          :option="updateOption"
          @submit="confirmVerifier"
        >
          <template slot="menuForm">
            <el-button
              size="small"
              icon="el-icon-close"
              @click="closeVerifierDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
  import {getList, getDetail, add, update, remove,getDeptList,planPublish} from "@/api/emer/drillplan";
  import {mapGetters} from "vuex";
  import { getToken } from "@/util/auth";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "演练名称",
              prop: "ylmc",
              align: "center",
              search: true,
              rules: [{
                required: true,
                message: "请输入演练名称",
                trigger: "blur"
              }]
            },
            {
              label: "演练地点",
              prop: "yldd",
              align: "center",
              rules: [{
                required: true,
                message: "请输入演练地点",
                trigger: "blur"
              }]
            },
            {
              label: "主办部门",
              prop: "zbbm",
              align: "center",
              type:"tree",
              search: true,
              dicData: [],
              rules: [{
                required: true,
                message: "请输入主办部门",
                trigger: "blur"
              }],
              props: {
                label: "title"
              }
            },
            {
              label: "演练方式",
              prop: "ylfs",
              align: "center",
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_drill_plan_ylfs",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入演练方式",
                trigger: "blur"
              }]
            },
            {
              label: "应急预案",
              prop: "yjya",
              align: "center",
              type:"select",
              dicUrl: "/api/emerDrillPlan/drillplan/getYamcList",
              props: {
                value: "yamc"
              },
              rules: [{
                required: true,
                message: "请输入应急预案",
                trigger: "blur"
              }]
            },
            {
              label: "演练级别",
              prop: "yljb",
              align: "center",
              search: true,
              type:"select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_drill_plan_yljb",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入演练级别",
                trigger: "blur"
              }]
            },
            {
              label: "计划定制日期",
              prop: "jhdzrq",
              align: "center",
              width:140,
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入计划定制日期",
                trigger: "blur"
              }]
            },
            {
              label: "计划演练日期",
              prop: "jhylrq",
              align: "center",
              width:140,
              type: "datetime",
              format: "yyyy-MM-dd hh:mm:ss",
              valueFormat: "yyyy-MM-dd hh:mm:ss",
              rules: [{
                required: true,
                message: "请输入计划演练日期",
                trigger: "blur"
              }]
            },
            {
              label: "计划定制人",
              prop: "jhdzr",
              align: "center",
              rules: [{
                required: true,
                message: "请输入计划定制人",
                trigger: "blur"
              }]
            },
            {
              label: "评价人",
              prop: "pjr",
              align: "center",
              dicUrl: "/api/emerRectify/rectify/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              width:"60px",
              addDisplay: false,
              editDisplay: false,
              hide: false,
            },
            {
              label: "评价设置",
              prop: "pjsz",
              align: "center",
              width:110,
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: false,
            },
            {
              label: "相关附件",
              prop: "xgfj",
              align: "center",
              span: 24,
              slot: true,
              formslot: true,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "请输入相关附件",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              maxlength:500,
              span: 24,
              minRows: 6,
              hide: true,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
            {
              label: "发布状态",
              prop: "fbzt",
              align: "center",
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: false,
            },
          ]
        },
        data: [],
        // 附件
        xgfjFileList: [],
        downloadHead: "/api/fileManager/download/",
        SetHeaders: { "Blade-Auth": getToken() },
        // 弹窗：评价设置
        verifierDialog: false,
        selectedSettingId:{},
        updateObj:{},
      };
    },
    computed: {
      ...mapGetters(["permission"]),

      updateOption() {
        return {
          size: "small",
          submitText: "确 定",
          labelWidth: 110,
          mockBtn: false,
          printBtn: false,
          emptyBtn: false,
          column: [
            {
              label: "评价人",
              prop: "pjr",
              span: 12,
              type: "select",
              dicUrl: "/api/emerRectify/rectify/getPersonInfo",
              props: {
                label: "name",
                value: "id",
              },
              rules: [{
                required: true,
                message: "请输入核实人",
                trigger: "blur"
              }]
            },

          ]
        }
      },
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.drillplan_add, false),
          viewBtn: this.vaildData(this.permission.drillplan_view, false),
          delBtn: this.vaildData(this.permission.drillplan_delete, false),
          editBtn: this.vaildData(this.permission.drillplan_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },

    mounted() {
      this.initData();
    },
    methods: {
      // 初始化数据
      initData() {
        var tenantId = JSON.parse( localStorage.getItem("saber-tenantId") ).content;
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "zbbm");
          column.dicData = res.data.data;
        }).then(() => {
        });
      },

      /**
       * 弹窗：添加评价人员
       */

      // 打开人员信息弹窗
      handleVerifier(row) {
        this.selectedSettingId = row;
        this.updateObj = this.formatUpdateObj(row);
        this.verifierDialog = true;
      },

      // 格式化评价设置数据
      formatUpdateObj() {
        var data = {
          pjr: "",
        };
        return data;
      },

      // 确定人员
      confirmVerifier() {
        this.$refs.updateForm.validate((vaild,done)=>{
          if(vaild){
            this.selectedSettingId.pjr= this.updateObj.pjr
            update(this.selectedSettingId).then(res => {
              if(res.data.success) {
                this.closeVerifierDialog();
                this.page.currentPage = 1;
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              }
            });
            done();
          }
        })
      },

      // 关闭、取消评价设置弹窗
      closeVerifierDialog() {
        this.selectedSettingId = {};
        this.verifierDialog = false;
      },

      rowSave(row, done, loading) {
        if (row.jhdzrq>row.jhylrq){
          console.log(row.jhylrq)
          console.log(row.jhylrq)
          this.$message.warning("计划演练日期填写错误,需大于计划定制日期");
          loading();
          return
        }
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if (row.jhdzrq>row.jhylrq){
          console.log(row.jhylrq)
          console.log(row.jhylrq)
          this.$message.warning("计划演练日期填写错误,需大于计划定制日期");
          loading();
          return
        }
        const updateData = {
          id: row.id,
          ylmc: row.ylmc,
          yldd: row.yldd,
          zbbm: row.zbbm,
          ylfs: row.ylfs,
          yjya: row.yjya,
          yljb: row.yljb,
          jhdzrq: row.jhdzrq,
          jhylrq: row.jhylrq,
          jhdzr: row.jhdzr,
          xgfj: row.xgfj,
          fbzt:row.fbzt,
          bz: row.bz,
          bladeDeptId: row.bladeDeptId,
          tenantId: row.tenantId,
          createUser: row.createUser,
          createDept: row.createDept,
          createTime: row.createTime,
          isDeleted:row.isDeleted,
        };
        update(updateData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (type === "edit") {
          if (this.form.fbzt === 1) {
            this.$message.warning("当前计划已发布不可编辑修改!");
            return;
          }
        }
        this.xgfjFileList = [];
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            if (type === "edit") {
              this.xgfjFileList.push({
                name: this.form.bladeFile.fileName,
                response: {
                  code: 200,
                  success: true,
                  msg: "操作成功",
                  data: this.form.bladeFile
                }
              });
            }
          });
        }
        done();
      },

      // 查看演练评价信息
      viewDrill(){

      },

      // 上传附件前
      beforeUploadXGFJ() {
        const isLimit = this.xgfjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传附件成功
      uploadXGFJSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.xgfjFileList = fileList;
        this.form.xgfj = response.data.id;
      },

      // 删除附件
      handleRemoveXGFJ(file, fileList) {
        this.xgfjFileList = fileList;
        this.form.xgfj = "";
      },

      // 发布应急预案
      publishPlan(id, loading) {
        planPublish(id).then(() => {
          this.onLoad(this.page);
          this.$message.success("发布成功!");
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .emerDrillPlan {
    .avue-crud {
      .avue-crud__search {
        .avue-form__row:nth-child(1) {
          .el-form-item__label {
            text-align: unset;
            width: 90px !important;
          }

          .el-form-item__content {
            margin-left: 90px !important;
          }
        }
      }
    }

    .enclosure_div {
      a {
        font-size: 12px;
        color: #409eff;

        i {
          margin-right: 5px;
        }
      }
    }
  }
</style>
